package com.dmz.java.objectReference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 软引用缓存
 * @author NUC
 *
 */
public class SoftReferenceCache {
	private ConcurrentHashMap<String,SoftReference<Object>> cacheMap=new ConcurrentHashMap<>();
    private ReferenceQueue<Object> refQueue=new ReferenceQueue<Object>();
    
    public void put(String key,Object value) {
    	SoftReference<Object> softReference=new SoftReference<>(value,refQueue);
    	cacheMap.put(key, softReference);
    }
    
    public Object get(String key) {
    	SoftReference<Object> softReference=cacheMap.get(key);
    	if(softReference==null) {
    		return null;
    	}
    	return softReference.get();
    }
    /**
     * 
     * @param args
     */
    public static void main(String args[]) {
    	byte[] bytes = new byte[2*1024 *1024];
    	SoftReferenceCache cache=new SoftReferenceCache();
    	cache.put("1", bytes);
    	for(int i=0;i<50;i++) {
    		bytes = new byte[2*1024 *1024];
    		System.out.println(cache.get("1"));
    		cache.put("1:"+i, bytes);
    	}
    	for(int i=0;i<50;i++) {
    		System.out.println(cache.get("1:"+i));
    	}
    }
}
